package com.hong.springboot.listener;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.hong.springboot.api.IUserService;
import com.hong.springboot.entity.User;
import com.hong.springboot.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.jms.TextMessage;

/**
 * @author: csh
 * @Date: 2021/3/16 11:14
 * @Description:用户监听
 */
@Service
@Log4j2
public class UserListener {

    @Reference
    private IUserService userService;

    /**
     *
     * 功能描述: 基于队列添加
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2021/4/20 10:56
     */
    @JmsListener(destination = "${spring.activemq.queue}",containerFactory = "jmsListenerContainerQueue")
    public void onMessage(TextMessage msg) {
        log.info("进入队列消费");
        if(null==msg){
            return;
        }
        try {
            User user = JSONObject.parseObject(msg.getText(),User.class);
            log.info("最终要添加的值{}",JSONObject.toJSONString(user));
            DataResponse<Boolean> save = userService.reallySave(user);
            if(save==null || !save.getData()){
                log.info("添加失败，原因{}",JSONObject.toJSONString(save));
            }
        }catch (Exception e){
            log.error("添加出错",e);
        }
    }

    @JmsListener(destination = "${spring.activemq.topic}",containerFactory = "jmsListenerContainerTopic")
    public void onMessage2(TextMessage msg) {
        log.info("进入topic消费");
        if(null==msg){
            return;
        }
        try {
            User user = JSONObject.parseObject(msg.getText(),User.class);
            log.info("最终要添加的值{}",JSONObject.toJSONString(user));
            DataResponse<Boolean> save = userService.reallySave(user);
            if(save==null || !save.getData()){
                log.info("添加失败，原因{}",JSONObject.toJSONString(save));
            }
        }catch (Exception e){
            log.error("添加出错",e);
        }
    }

}
